package com.llb666.java.leetcode.node;

/**
 * 链表反转
 * @author 斌~
 * @version 1.0
 * @date 2021/4/23 下午11:33
 */
public class 链表反转 {

    /**
     * 内部类 -- 链表节点
     */
    static class ListNode{
        int
                val;
        ListNode next;
        public ListNode(int val,ListNode next){
            this.val =val;
            this.next =next;
        }
    }

    /**
     * 方法1：迭代
     */
    public static ListNode iterate(ListNode head){
        //定义prev节点，next节点 --- 前一个节点 后一个节点
        ListNode prev = null,next;
        //当前节点
        ListNode curr =head;
        while (curr !=null){
            //思路：下一个节点的next指向当前prev，
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

    /**
     * 方法2：递归
     */
    public static ListNode recursion(ListNode head){
        if(head == null || head.next == null){
            return head;
        }
        ListNode newHead = recursion(head.next);
        head.next.next=head;
        head.next =null;
        return newHead;
    }

    public static void main(String[] args) {
        ListNode node5 = new ListNode(5,null);
        ListNode node4 = new ListNode(4,node5);
        ListNode node3 = new ListNode(3,node4);
        ListNode node2 = new ListNode(2,node3);
        ListNode node1 = new ListNode(1,node2);

        ListNode prev = recursion(node1);
        System.out.println("-----");

        while (prev !=null){
            System.out.print(prev.val);
            prev = prev.next;
        }


    }
}
